package com.bie.action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayResponse;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayMonitorService;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayMonitorServiceImpl;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.service.impl.AlipayTradeWithHBServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.woke.bean.UserBean;
import com.woke.dao.CjPrice;
import com.woke.dao.Customer;
import com.woke.dao.User;
import com.woke.entity.Cache;
import com.woke.utils.CacheManager;
import com.woke.utils.MatrixToImageWriterUtils;
import com.woke.wxpay.MyConfig;

import net.sf.json.JSONObject;
import net.ycii.api.UserApi;
import net.ycii.api.WeiXinApi;
import net.ycii.entity.WeiXinUser;

public class WelcomeAction implements Action, ServletRequestAware, ServletResponseAware, ServletContextAware {
	private HttpServletRequest request;
	private HttpServletResponse responese;
	private HttpSession session;
	private ServletContext application;
	
	
	// 支付宝当面付2.0服务
    private static AlipayTradeService   tradeService;

    // 支付宝当面付2.0服务（集成了交易保障接口逻辑）
    private static AlipayTradeService   tradeWithHBService;

    // 支付宝交易保障接口服务，供测试接口api使用，请先阅读readme.txt
    private static AlipayMonitorService monitorService;
    
    static{
    	/** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();

        // 支付宝当面付2.0服务（集成了交易保障接口逻辑）
        tradeWithHBService = new AlipayTradeWithHBServiceImpl.ClientBuilder().build();

        /** 如果需要在程序中覆盖Configs提供的默认参数, 可以使用ClientBuilder类的setXXX方法修改默认参数 否则使用代码中的默认设置 */
        monitorService = new AlipayMonitorServiceImpl.ClientBuilder()
            .setGatewayUrl("http://mcloudmonitor.com/gateway.do").setCharset("GBK")
            .setFormat("json").build();
    }
    
	/**
	 * 跳装首页欢迎页
	 * @return
	 * @throws Exception
	 */
	public String toWelcome() throws Exception {
		System.out.println("生成微信二维码 start");
		MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);

        //生成微信二維碼
        WxPay(wxpay);
		
        //生成支付宝二维码
        //trade_precreate();
        
		return "success";
	}
	
	/**
	 * 生成微信支付二維碼
	 * @param wxpay
	 */
	private void WxPay(WXPay wxpay)
	{
		Map<String, String> data = new HashMap<String, String>();
        data.put("body", "抽奖大活动");//商品描述
        data.put("out_trade_no", String.valueOf(System.currentTimeMillis()) + "123");//商户订单号，不可重复
        data.put("device_info", "");//设备号
        data.put("fee_type", "CNY");//标价币种(默认人民币)
        data.put("total_fee", "1");//标价金额，单位：分
        data.put("spbill_create_ip", "106.14.157.195");//终端IP
        data.put("notify_url", "http://www.czwkyx.com/WoKeCJ/WxNotify");//通知地址，必须是外网能访问的地址
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", UUID.randomUUID().toString().replace("-", "").toLowerCase());//商品ID
        
        System.out.println("订单号：" + data.get("out_trade_no") + "," + "产品ID长度:" + data.get("product_id").length());
        
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println("返回结果:" + resp);
            String codeUrl = resp.get("code_url");
            System.out.println("返回的二维码url：" + codeUrl);
            
            String tempPath = request.getSession().getServletContext().getRealPath("/") + "images/" + "weixin.png";
    		MatrixToImageWriterUtils.generatorImage(tempPath, 518, 518, codeUrl);
    		System.out.println("覆盖二维码成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
    // 测试当面付2.0生成支付二维码
    public void trade_precreate() {
        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = "tradeprecreate" + System.currentTimeMillis()
                            + (long) (Math.random() * 10000000L);

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = "xxx品牌xxx门店当面付扫码消费";

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = "0.01";

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        String body = "购买商品3件共20.00元";

        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");

        // 支付超时，定义为120分钟
        String timeoutExpress = "120m";

        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "xxx小面包", 1000, 1);
        // 创建好一个商品后添加至商品明细列表
        goodsDetailList.add(goods1);

        // 继续创建并添加第一条商品信息，用户购买的产品为“黑人牙刷”，单价为5.00元，购买了两件
        GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "xxx牙刷", 500, 2);
        goodsDetailList.add(goods2);

        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
            .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
            .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
            .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
            .setTimeoutExpress(timeoutExpress)
            .setNotifyUrl("http://www.test-notify-url.com")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
            .setGoodsDetailList(goodsDetailList);

        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
            	System.out.println("支付宝预下单成功: )");
                AlipayTradePrecreateResponse response = result.getResponse();
                dumpResponse(response);

                // 需要修改为运行机器上的路径
                String tempPath = request.getSession().getServletContext().getRealPath("/") + "images/" + "alipay.png";
        		MatrixToImageWriterUtils.generatorImage(tempPath, 543, 543, response.getQrCode());
                break;

            case FAILED:
                System.out.println("支付宝预下单失败!!!");
                break;

            case UNKNOWN:
            	System.out.println("系统异常，预下单状态未知!!!");
                break;

            default:
            	System.out.println("不支持的交易状态，交易返回异常!!!");
                break;
        }
    }
    
    //简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            System.out.println(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
            	System.out.println(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                    response.getSubMsg()));
            }
            System.out.println("body:" + response.getBody());
        }
    }
	
    /**
     * 支付寶回調
     * @param request
     * @param response
     * @throws Exception
     */
	public void alipayNotify() throws Exception {
		System.out.println("支付宝付款异步通知！");
		String message = "success";
		Map<String, String> params = new HashMap<String, String>();
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		// 验证签名
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, Configs.getAlipayPublicKey(), "UTF-8");
		} catch (AlipayApiException e) {
			e.printStackTrace();
			message = "failed";
		}
		if (signVerified) {
			System.out.println("验证签名成功！");
			JSONObject json = JSONObject.fromObject(params);
			System.out.println("支付寶回調字符串: " + json.toString());
			// 若参数中的appid和填入的appid不相同，则为异常通知
			if (!Configs.getAppid().equals(params.get("app_id"))) {
				System.out.println("与付款时的appid不同，此为异常通知，应忽略！");
				message = "failed";
			} else {
				String outtradeno = params.get("out_trade_no");
				System.out.println(outtradeno + "号订单回调通知。");
				// 在数据库中查找订单号对应的订单，并将其金额与数据库中的金额对比，若对不上，也为异常通知
				String status = params.get("trade_status");
				if (status.equals("WAIT_BUYER_PAY")) { // 如果状态是正在等待用户付款
				} else if (status.equals("TRADE_CLOSED")) { // 如果状态是未付款交易超时关闭，或支付完成后全额退款
				} else if (status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED")) { // 如果状态是已经支付成功
					// 成功 更新状态  保存數據
					
					
					
					
				} else {
//					weixinpayBack.updateAccOrder(outtradeno);
				}
				System.out.println(outtradeno + "订单的状态已经修改为" + status);
			}
		} else { // 如果验证签名没有通过
			message = "failed";
			System.out.println("验证签名失败！");
		}
		BufferedOutputStream out = new BufferedOutputStream(responese.getOutputStream());
		out.write(message.getBytes());
		out.flush();
		out.close();
	}

	/**
	 * 微信支付成功回调开始
	 */
	public void WxNotify()
	{
		System.out.println("支付成功回调开始 start");
		String notifyData = "";
        try {
            InputStream is = request.getInputStream();
            StringBuffer sb = new StringBuffer();  
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((s = in.readLine()) != null){  
                sb.append(s);  
            }  
            in.close();  
            is.close();

            notifyData = sb.toString();
            System.out.println("微信支付回调返回字符串: " + notifyData);
            
            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
                // 签名正确
                // 进行处理。
                // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            	System.out.println("支付成功");
            	JSONObject json = JSONObject.fromObject(notifyMap);
            	System.out.println("微信回調返回JSON字符串偽: " + json.toString());
            	
            	
            	//缓存微信Token，默认失效时间7200秒
        		String token = "";
        		Cache tokenCache = CacheManager.getCacheInfo("WxConfigParam");
        		if(tokenCache == null || tokenCache.isExpired() == true)
        		{
        			MyConfig myConfig = new MyConfig();
        			token = WeiXinApi.token(myConfig.getAppID(), myConfig.getAppSecret()).getAccess_token();//获取token
        			
        			//存储缓存信息
        			Cache cache = new Cache();
        			cache.setExpired(false);
        			cache.setValue(token);
        			cache.setTimeOut(System.currentTimeMillis()+6600000l);//失效时间(1个小时50分失效)
        			CacheManager.putCache("WxConfigParam", cache);
        		}
        		else
        		{
        			token = (String)tokenCache.getValue();
        		}
        		
        		System.out.println("access_token:" + token);
        		
        		WeiXinUser author =UserApi.getWeiXinUserInfo(notifyMap.get("openid"),token);
            	JSONObject authorUser = JSONObject.fromObject(author);
            	System.out.println("獲取微信用戶信息如下: " + authorUser.toString());
            	
            	
            	
            	System.out.println("回調時重新生成二維碼 start");
            	WxPay(wxpay);
            	System.out.println("回調時重新生成二維碼 start");
            }
            else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
            	System.out.println("支付失败");
            }
            
            responese.setContentType("text/html;charset=UTF-8");
            OutputStream os = responese.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(notifyData);
            oos.flush();
            oos.close();
            os.close();
        } catch (Exception e) {
        	System.out.println("微信支付回调异常: " + e.getMessage());
            e.printStackTrace();
        }
	}


	@Override
	public void setServletContext(ServletContext application) {
		this.application = application;
		
	}


	public HttpServletRequest getRequest() {
		return request;
	}


	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}


	public HttpServletResponse getResponese() {
		return responese;
	}


	public void setResponese(HttpServletResponse responese) {
		this.responese = responese;
	}


	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public ServletContext getApplication() {
		return application;
	}


	public void setApplication(ServletContext application) {
		this.application = application;
	}


	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.responese = response;
		
	}


	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
		
	}


	@Override
	public String execute() throws Exception {
		return null;
	}
	
	public static void main(String[] args) {
		CjPrice dao=new CjPrice();
	  List<CjPrice> list = dao.selectLend(1, 1);
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					CjPrice s = list.get(i);
					System.out.println(s.getCusprice());
				}
			}}
	
}
